// 用电过往排行
var numberFormate = iot.getNumberFormat("0.00");
var timeNotYearFormatMap = {
    'year': "%Y",
    'month': "%m",
    'day': "%m-%d",
    'hour': "%m-%d %H"
};
dev.action = function(resp,param){
    //获取工厂名称
    var factoryName = getFactoryName(param.workSpaceName);
    //是否算总还是单
    var totalOrSingle = param.selectType;
    if (totalOrSingle == null){
        totalOrSingle = "total";
    }
    var theTime = param.time;
    var workSpace = param.workSpace;
    var db = iot.db();
    var format;
    var resultData = {
        content : iot.list()
    };

    var theTimeNotYear =  '';
    if(theTime && theTime.length() > 4){
        theTimeNotYear = theTime.substring(5,theTime.length());
    }
    var timeType = iot.getTimeByFormat(theTime);
    var timeDataList = getNearlyFourYears(param.time);
    var year = '';
    for (var index = 0; index < timeDataList.length; index++){
        year = year + timeDataList[index] + ",";
    }
    year = year + 0;
    format = timeNotYearFormatMap[timeType];
    var yieldId = getFactoryYieldId(factoryName)
    var electResult = db.qry("select DATE_FORMAT(dev_win.the_time,'%Y') yearIx, SUM(dev_win.dvalue) totalSum" +
        " from iot_dev_data_win dev_win, (select * from energy_struc_prop where type = 1 and field_type = '用量' and energy_struc_id = "+ workSpace +") esp" +
        " where dev_win.dev_id = esp.dev_id and dev_win.data_type = esp.name" +
        " and DATE_FORMAT(dev_win.the_time,'" + format + "') like '%"+ theTimeNotYear +"%'" +
        " and DATE_FORMAT(dev_win.the_time,'%Y') in ("+ year +")" +
        " group by yearIx" +
        " ORDER BY yearIx desc");

    var yieldResult = db.qry("select DATE_FORMAT(win.the_time,'%Y') yearIx,SUM(dvalue) totalSum \n" +
        "from iot_dev_data_win win\n" +
        "where dev_id = "+ yieldId +" \n" +
        "and DATE_FORMAT(win.the_time,'" + format + "') like '%"+ theTimeNotYear +"%'\n" +
        "group by yearIx ORDER BY totalSum DESC");
    var resultList = iot.list();

    var count = 0;
    var preValue = "";
    var totalSum = 0;
    // 开始组装数据
    if (electResult) {
        electResult.forAll(function (item) {
            // 只有数值不一样，排名才会上升，将当前值赋值给preValue
            if (!item.totalSum.equals(preValue)) {
                preValue = item.totalSum;
                ++count;
            }
            var totalYield = 0;
            totalSum = item.totalSum;

            yieldResult.forAll(function (yieldItem) {
                if (item.yearIx.equals(yieldItem.yearIx)) {
                    totalYield = yieldItem.totalSum;
                }
            });

            //判断当前选择总数还是单车
            if (totalOrSingle.equals("single")) {
                if (totalYield){
                    totalSum = totalSum/totalYield;
                }
                if (totalYield === 0){
                    totalSum = 0;
                }
            }
            resultList.add({rank: count, year: item.yearIx, useNum: numberFormate.format(totalSum), increase: "0%"});
        })
    }

    // 如果没有timeDataList年份的数据，则赋值为0
    for (var i in timeDataList) {
        var flag = false;
        for (var key in resultList) {
            if (resultList[key].year.equals(timeDataList[i])) {
                flag = true;
            }
        }
        if (!flag) {
            resultList.add({rank: count + 1, year: timeDataList[i], useNum: 0, increase: "0%"});
        }
    }
    // 计算同比年/月/日涨幅
    var increaseList = iot.list();
    for (var i in timeDataList) {
        if (i == 0) {
            continue;
        }
        var currentUseNum = 0, preUseNum = 0; // 存储当前年份总量和同比时间的总量
        for (var j in resultList) {
            if (timeDataList[i].equals(resultList[j].year)) {
                currentUseNum = resultList[j].useNum;
            }
            if (timeDataList[i - 1].equals(resultList[j].year)) {
                preUseNum = resultList[j].useNum;
            }
        }
        if (currentUseNum == 0 || preUseNum == 0) { // 只要有一年的总量为0，则计算涨幅没有意义
            continue;
        }
        var increase = (currentUseNum - preUseNum) / preUseNum; // 计算同比涨幅
        var toFixedIncrease = (100 * increase).toFixed(2); // 保留两位小数
        increaseList.add({year: timeDataList[i], increase: toFixedIncrease + "%"})
    }

    // 修改同比涨幅
    for (var i in resultList) {
        // 开始遍历修改resultList的同比涨幅increase
        var flag = false;
        var increase;
        for (var j in increaseList) {
            if (resultList[i].year.equals(increaseList[j].year)) {
                flag = true;
                increase = increaseList[j].increase;
            }
        }
        if (flag) {
            resultList[i].increase = increase;
        }
    }
    // 时间格式转换成和theTime一样
    /*for (var i in resultList) {
        resultList[i].year = getTime(resultList[i].year, theTime);
    }*/
    // JS调用Java排序方法，根据value进行降序排列
    var Collections = Java.type("java.util.Collections");
    var Comparator = Java.type("java.util.Comparator")
    var Printer = Java.extend(Comparator, {
        compare : function (o1, o2) {
            var value1 = Number(o1.year);
            var value2 = Number(o2.year);
            if (value1 > value2) {
                return -1;
            }
            if (value1 > value2) {
                return 1;
            }
            return 0;
        }
    })
    Collections.sort(resultList, new Printer());
    resultData.content = resultList;
    resp.setJsData(resultData);
}